#!/usr/bin/env python3
"""
DSL语法迁移脚本 - 简化版
专注于基本的字符串替换，避免复杂的YAML解析

使用方法:
python scripts/migrate-dsl-syntax-simple.py [目录路径]
"""

import os
import re
import sys
from pathlib import Path
import argparse
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class SimpleDSLMigrator:
    """简化的DSL语法迁移器"""
    
    def __init__(self):
        self.processed_files = []
        self.error_files = []
        
    def migrate_file(self, file_path: Path) -> bool:
        """迁移单个文件"""
        try:
            logger.info(f"正在处理文件: {file_path}")
            
            # 读取文件内容
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            original_content = content
            
            # 应用语法替换
            content = self._apply_replacements(content)
            
            # 如果内容有变化，写回文件
            if content != original_content:
                # 创建备份
                backup_path = file_path.with_suffix(file_path.suffix + '.backup')
                with open(backup_path, 'w', encoding='utf-8') as f:
                    f.write(original_content)
                logger.info(f"已创建备份: {backup_path}")
                
                # 写入新内容
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                
                logger.info(f"✅ 已更新文件: {file_path}")
                self.processed_files.append(str(file_path))
                return True
            else:
                logger.info(f"⏭️  文件无需更新: {file_path}")
                return True
                
        except Exception as e:
            logger.error(f"❌ 处理文件失败 {file_path}: {str(e)}")
            self.error_files.append(str(file_path))
            return False
    
    def _apply_replacements(self, content: str) -> str:
        """应用所有语法替换"""
        
        # 1. 基本字段名称替换
        replacements = [
            ('fields:', 'attributes:'),
            ('relations:', 'associations:'),
            ('relationships:', 'associations:'),
            ('emits:', 'events:'),
        ]
        
        for old, new in replacements:
            content = content.replace(old, new)
        
        # 2. 关系类型标准化
        relation_types = [
            ('hasMany', 'one-to-many'),
            ('belongsTo', 'many-to-one'),
            ('hasOne', 'one-to-one'),
            ('belongsToMany', 'many-to-many'),
            ('oneToOne', 'one-to-one'),
            ('oneToMany', 'one-to-many'),
            ('manyToOne', 'many-to-one'),
            ('manyToMany', 'many-to-many'),
        ]
        
        for old_type, new_type in relation_types:
            # 替换 type: 后面的关系类型
            content = re.sub(f'type:\\s*{old_type}', f'type: {new_type}', content)
        
        # 3. 处理布尔属性转换为rules格式
        # 注意：这里使用更精确的正则表达式来避免误替换
        
        # 处理 primary: true
        content = re.sub(r'^(\s+)primary:\s*true\s*$', r'\1rules: [primary]', content, flags=re.MULTILINE)
        
        # 处理 unique: true  
        content = re.sub(r'^(\s+)unique:\s*true\s*$', r'\1rules: [unique]', content, flags=re.MULTILINE)
        
        # 处理 required: true
        content = re.sub(r'^(\s+)required:\s*true\s*$', r'\1rules: [required]', content, flags=re.MULTILINE)
        
        # 移除 false 值的属性
        content = re.sub(r'^(\s+)(primary|unique|required):\s*false\s*\n', '', content, flags=re.MULTILINE)
        
        # 4. 处理format属性
        content = re.sub(r'^(\s+)format:\s*(\w+)\s*$', r'\1rules: [{ format: \2 }]', content, flags=re.MULTILINE)
        
        return content
    
    def migrate_directory(self, directory: Path, pattern: str = "*.yml") -> None:
        """迁移目录下的所有文件"""
        logger.info(f"开始迁移目录: {directory}")
        
        if not directory.exists():
            logger.error(f"目录不存在: {directory}")
            return
        
        # 查找所有匹配的文件
        yaml_files = list(directory.rglob(pattern))
        yaml_files.extend(list(directory.rglob("*.yaml")))
        
        if not yaml_files:
            logger.warning(f"在目录 {directory} 中未找到YAML文件")
            return
        
        logger.info(f"找到 {len(yaml_files)} 个文件需要处理")
        
        # 处理每个文件
        for file_path in yaml_files:
            self.migrate_file(file_path)
    
    def print_summary(self) -> None:
        """打印迁移摘要"""
        print("\n" + "="*60)
        print("DSL语法迁移完成")
        print("="*60)
        print(f"✅ 成功处理文件: {len(self.processed_files)}")
        print(f"❌ 处理失败文件: {len(self.error_files)}")
        
        if self.processed_files:
            print("\n已处理的文件:")
            for file_path in self.processed_files:
                print(f"  - {file_path}")
        
        if self.error_files:
            print("\n处理失败的文件:")
            for file_path in self.error_files:
                print(f"  - {file_path}")
        
        print("\n💡 提示:")
        print("  - 原文件已备份为 .backup 后缀")
        print("  - 请运行测试验证迁移结果")
        print("  - 如有问题可从备份文件恢复")

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='DSL语法迁移工具 - 简化版')
    parser.add_argument('directory', nargs='?', default='.', 
                       help='要迁移的目录路径 (默认: 当前目录)')
    parser.add_argument('--pattern', default='*.yml', 
                       help='文件匹配模式 (默认: *.yml)')
    
    args = parser.parse_args()
    
    directory = Path(args.directory).resolve()
    
    print("DSL语法迁移工具 - 简化版")
    print("="*40)
    print(f"目标目录: {directory}")
    print(f"文件模式: {args.pattern}")
    print()
    
    # 创建迁移器并执行迁移
    migrator = SimpleDSLMigrator()
    migrator.migrate_directory(directory, args.pattern)
    migrator.print_summary()

if __name__ == '__main__':
    main()